import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs'
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject'
import { setMd5 } from '@/utils'

const http = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  timeout: 1000 * 1800,
  withCredentials: true
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  config.headers['token'] = Cookies.get('token') || ''
  
  const type = 'common';
  const time = new Date().valueOf();
  const thisurl = config.url;
  const suger = 'FastBoot.RickSun.Sugar';
  const jg = '-';
  const sign = setMd5(type + jg + thisurl + jg + time + jg + suger);
  const passToken = type + jg + time + jg + sign;
  config.headers['passToken'] = passToken;
  
  if( thisurl === '/common/upload/uploadFile' ){
    config.headers['Content-Type'] = 'multipart/form-data'
  }
  
  if( thisurl === '/pc/database/downLoadCode' ){
	  config.responseType = 'blob'
  }
  
  // console.log(JSON.stringify(config))
  
  // 默认参数
  var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
	  // console.log("------>get:"+JSON.stringify(config.params));
	  // console.log("------>get_config:"+JSON.stringify(config));
    config.params = {
      ...config.params,
      ...{ '_t': new Date().getTime() }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
	
  var resUrl = response.config.url;
  if (
	( response.data.code === 401 ) 
		&& resUrl.indexOf('systemUser/login') === -1
	) {
	clearLoginInfo()
    router.replace({ name: 'login' })
    return Promise.reject(response.data.msg)
  }
  return response
}, error => {
  console.error(error)
  return Promise.reject(error)
})

export default http
